<template>
	<div>
		<Table :columns="columns" :data="rows" />
		<el-button v-if="isEdit" class="add-btn" @click="handleAdd">
			<i class="el-icon-plus"></i>
			添加
		</el-button>
	</div>
</template>

<script>
import Table from '@/components/Table'
import { TableColumns } from '@/components/TableContainer'
import { rebateRender } from './utils'
const initRow = (vals = {}) => {
	return {
		isEdit: false,
		serialNo: undefined,
		validBetAmount: undefined,
		activeUsers: undefined,
		addActiveUsers: undefined,
		texasCommission: undefined,
		texasInsuranceCommission: undefined,
		otherCommission: undefined,
		id: new Date().getTime(),
		...vals
	}
}

export default {
	name: 'RebateTable',
	components: {
		Table
	},
	props: {
		value: {
			type: Array,
			default: () => [
				initRow({
					isEdit: true,
					serialNo: 1
				})
			]
		},
		isEdit: {
			type: Boolean,
			default: false
		},
		checkMax: {
			type: Function,
			default: undefined
		},
		clearValidate: {
			type: Function,
			default: null
		}
	},
	data() {
		const amountRule = {
			validator: (rule, val, callback) => {
				const path = rule['field'].split('.')
				const field = path[2]
				const index = Number(path[1])
				if (val !== 0 && !val) {
					return callback(new Error(`不能为空`))
				}
				const prev = this.rows[index - 1] || {}
				const next = this.rows[index + 1] || {}

				if (prev || next) {
					const min = prev[field]
					const max = next[field]
					if (min || max) {
						if (min && max && (val < min || val > max)) {
							return callback(
								new Error(`不大于${max}, 不小于${min}`)
							)
						}

						if (min && val < min) {
							return callback(new Error(`不小于${min}`))
						}
						if (max && val > max) {
							return callback(new Error(`不能大于${max}`))
						}
					}
				}
				return callback()
			},
			trigger: 'blur'
		}

		const editAmountRender = ({ row, column, $index }) => {
			const prop = column.property
			return (
				<el-form-item
					rules={amountRule}
					prop={`commissionRateList.${$index}.${prop}`}
				>
					<div class='edit-number'>
						<span>
							≥ {prop === 'validBetAmount' ? '$' : ''} &nbsp;
						</span>
						<el-input-number
							controls={false}
							placeholder='0'
							onChange={(newVal) =>
								this.handleItemChange(prop, $index, newVal)
							}
							value={this.value[$index][prop]}
							min={0}
						/>
					</div>
				</el-form-item>
			)
		}

		const rule = {
			validator: (rule, val, callback) => {
				const path = rule['field'].split('.')
				const field = path[2]
				const index = Number(path[1])
				if (val !== 0 && !val) {
					return callback(new Error(`不能为空`))
				}

				const prev = this.rows[index - 1] || {}
				const next = this.rows[index + 1] || {}

				if (prev || next) {
					const min = prev[field]
					const max = next[field]
					if (min || max) {
						if (min && max && (val < min || val > max)) {
							return callback(
								new Error(`不大于${max}, 不小于${min}`)
							)
						}

						if (min && val < min) {
							return callback(new Error(`不小于${min}`))
						}
						if (max && val > max) {
							return callback(new Error(`不能大于${max}`))
						}
					}
				}
				const err = this.checkMax(field, val)
				if (err) {
					return callback(new Error(err))
				}
				return callback()
			},
			trigger: 'blur'
		}
		const editPointRender = ({ row, column, $index }) => {
			const prop = column.property
			return (
				<el-form-item
					rules={rule}
					prop={`commissionRateList.${$index}.${prop}`}
				>
					<div class='edit-number'>
						<el-input-number
							precision={3}
							min={0}
							controls={false}
							placeholder={this.value[prop] || '0.000'}
							value={this.value[$index][prop]}
							onChange={(newVal) =>
								this.handleItemChange(prop, $index, newVal)
							}
						/>
						<span>&nbsp;%</span>
					</div>
				</el-form-item>
			)
		}

		const headerRender = (label, tips) => {
			return (
				<div class='header'>
					{label}
					<p>团队返佣</p>
					{tips && (
						<el-tooltip
							content={`${label}团队返佣：${tips}`}
							placement='top-start'
							effect='dark'
						>
							<i class='el-icon-question' />
						</el-tooltip>
					)}
				</div>
			)
		}

		return {
			columns: [
				{
					label: '#',
					minWidth: '40px',
					customRender: ({ $index }) => {
						return $index + 1
					}
				},
				TableColumns.edit({
					minWidth: '140px',
					label: '代理净输赢',
					prop: 'validBetAmount',
					editRender: editAmountRender,
					customRender: ({ row }) => row.validBetAmount
				}),
				TableColumns.edit({
					minWidth: '120px',
					label: '本月活跃人数',
					prop: 'activeUsers',
					editRender: editAmountRender,
					customRender: ({ row }) => row.activeUsers
				}),
				TableColumns.edit({
					minWidth: '120px',
					header: () => {
						return (
							<div>
								本月新增有效
								<p>活跃人数</p>
							</div>
						)
					},
					prop: 'addActiveUsers',
					editRender: editAmountRender,
					customRender: ({ row }) => row.addActiveUsers
				}),
				TableColumns.edit({
					minWidth: '150px',
					prop: 'texasCommission',
					header: () =>
						headerRender(
							'德州-俱乐部',
							this.$t('agent.texasCommission_tips')
						),
					editRender: editPointRender,
					customRender: rebateRender
				}),
				TableColumns.edit({
					minWidth: '150px',
					prop: 'texasInsuranceCommission',
					header: () =>
						headerRender(
							'德州-保险',
							this.$t('agent.texasInsuranceCommission_tips')
						),
					editRender: editPointRender,
					customRender: rebateRender
				}),
				TableColumns.edit({
					minWidth: '150px',
					prop: 'otherCommission',
					header: () => headerRender('其他项目'),
					editRender: editPointRender,
					customRender: rebateRender
				}),
				{
					minWidth: '100px',
					label: '操作',
					isShow: () => this.isEdit,
					customRender: ({ row }) => {
						return (
							<el-button onClick={() => this.handleRemove(row)}>
								{' '}
								删除{' '}
							</el-button>
						)
					}
				}
			]
		}
	},
	computed: {
		rows() {
			if (this.value.length > 0) {
				return this.value.map((row) => {
					return {
						...row,
						isEdit: this.isEdit
					}
				})
			}
			return []
		}
	},
	created() {
		if (this.isEdit && this.value.length === 0) {
			this.handleAdd()
		}
	},
	methods: {
		handleItemChange(prop, index, newVal) {
			this.$emit(
				'change',
				this.value.map((item, ind) => {
					if (ind === index) {
						return Object.assign(item, {
							[prop]: newVal
						})
					}
					return item
				})
			)
		},
		handleAdd() {
			this.$emit(
				'input',
				this.value.concat(
					initRow({
						isEdit: this.isEdit,
						serialNo: this.rows.length + 1 || 1
					})
				)
			)
		},
		handleInit() {
			this.$emit('input', [
				initRow({
					isEdit: this.isEdit,
					serialNo: 1
				})
			])
		},
		handleRemove({ id }) {
			let delIndex
			let delRow
			const newItems = this.value.filter((row, index) => {
				if (row.id === id) {
					delIndex = index
					delRow = row
					return false
				}
				return true
			})

			Object.keys(delRow).forEach((k) => {
				this.clearValidate(`commissionRateList.${delIndex}.${k}`)
			})
			this.$message.success('删除成功')
			this.$emit('input', newItems)
		}
	}
}
</script>

<style scoped lang="scss">
::v-deep .edit-number {
	display: flex;
}

::v-deep .edit-number .el-input input {
	width: 90px;
	margin-left: 2px;
}

.add-btn {
	width: 300px;
	margin: 0 auto;
	margin-top: 10px;
}

.header {
	position: relative;

	.el-icon-question {
		position: absolute;
		font-size: 12px;
		top: 25px;
		right: 10px;
		cursor: pointer;
		&:after {
			font-size: 17px;
		}
	}
}
</style>
